package cn.ug.login.service.impl;

import cn.ug.analyse.bean.ChannelUserBean;
import cn.ug.bean.LoginBean;
import cn.ug.bean.type.LoginPlatform;
import cn.ug.bean.type.LoginSource;
import cn.ug.bean.type.OnlineType;
import cn.ug.login.service.LoginSessionService;
import cn.ug.service.impl.LoginInfoServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static cn.ug.util.ConstantUtil.COLON;

@Service
public class LoginSessionServiceImpl extends LoginInfoServiceImpl implements LoginSessionService {
	/** 最大保存时间（单位小时） */
	private static final long MAX_ACTIVE_HOURS = 30 * 24;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public LoginBean put(String key, LoginBean value) {
		loginCacheService.setCache(TYPE_NAME, key, value.getId(), MAX_ACTIVE_HOURS, TimeUnit.HOURS);
		String platform = LoginPlatform.APP.name();
		if (value != null && value.getLoginSource() != LoginSource.APP_ANDROID && value.getLoginSource() != LoginSource.APP_IOS) {
            platform = LoginPlatform.WEB.name();
        }
        loginCacheService.setCache(TYPE_NAME, KEY_PLATFORM + key, platform, MAX_ACTIVE_HOURS, TimeUnit.HOURS);
		loginCacheService.setCache(TYPE_NAME, KEY_ID + platform + COLON + value.getId(), key, MAX_ACTIVE_HOURS, TimeUnit.HOURS);
		loginCacheService.setCache(TYPE_NAME, KEY_OBJ + platform + COLON + value.getId(), value, MAX_ACTIVE_HOURS, TimeUnit.HOURS);
		return value;
	}

	@Override
	public LoginBean get(String key) {
		return get(key, true);
	}

	@Override
	public LoginBean remove(String key) {
		LoginBean obj = get(key, false);
		loginCacheService.deleteCache(TYPE_NAME, key);
        Object platformObj = loginCacheService.getCache(TYPE_NAME, KEY_PLATFORM + key);
        if (platformObj != null) {
            loginCacheService.deleteCache(TYPE_NAME, KEY_PLATFORM + key);
            String platform = (String)platformObj;
            if(null != obj && obj.getOnlineType() == OnlineType.ONLINE){
                loginCacheService.deleteCache(KEY_ID + platform + COLON + obj.getId());
                loginCacheService.deleteCache(KEY_OBJ + platform + COLON + obj.getId());
            }
        }
		return obj;
	}

	@Override
	public ChannelUserBean getchannelUserInfo(String key) {
		String userInfo = redisTemplate.opsForValue().get(key);
		if (StringUtils.isBlank(userInfo))
			return null;

		ChannelUserBean channelUserBean = JSONObject.parseObject(userInfo,ChannelUserBean.class);
		return channelUserBean;
	}
}

